// 档案数据接口
export interface ArchiveData {
  id: string
  relationship: string
  name: string
  idCard: string
  birthDate: string
  gender: string
  phone: string
  createTime: string
}

// 档案服务类
class ArchiveService {
  private readonly STORAGE_KEY = 'health_archives'

  // 获取所有档案
  getArchives(): ArchiveData[] {
    try {
      const data = localStorage.getItem(this.STORAGE_KEY)
      return data ? JSON.parse(data) : []
    } catch (error) {
      console.error('获取档案数据失败:', error)
      return []
    }
  }

  // 添加新档案
  addArchive(archive: Omit<ArchiveData, 'id' | 'createTime'>): ArchiveData {
    const newArchive: ArchiveData = {
      ...archive,
      id: this.generateId(),
      createTime: new Date().toISOString()
    }

    const archives = this.getArchives()
    archives.push(newArchive)
    this.saveArchives(archives)

    return newArchive
  }

  // 删除档案
  deleteArchive(id: string): boolean {
    const archives = this.getArchives()
    const filteredArchives = archives.filter(archive => archive.id !== id)
    
    if (filteredArchives.length !== archives.length) {
      this.saveArchives(filteredArchives)
      return true
    }
    return false
  }

  // 更新档案
  updateArchive(id: string, updates: Partial<ArchiveData>): boolean {
    const archives = this.getArchives()
    const index = archives.findIndex(archive => archive.id === id)
    
    if (index !== -1) {
      archives[index] = { ...archives[index], ...updates }
      this.saveArchives(archives)
      return true
    }
    return false
  }

  // 保存档案数据到本地存储
  private saveArchives(archives: ArchiveData[]): void {
    try {
      localStorage.setItem(this.STORAGE_KEY, JSON.stringify(archives))
    } catch (error) {
      console.error('保存档案数据失败:', error)
    }
  }

  // 生成唯一ID
  private generateId(): string {
    return Date.now().toString(36) + Math.random().toString(36).substr(2)
  }

  // 清空所有档案（用于测试）
  clearAll(): void {
    localStorage.removeItem(this.STORAGE_KEY)
  }
}

export const archiveService = new ArchiveService()
